<template>
  <div id="register">
    <el-form :model="form" status-icon :rules="rules" ref="registerForm" label-width="100px" class="demo-ruleForm">
      <h3 class="title">注册</h3>
      <el-form-item prop="username">
        <el-input type="text" v-model="form.username" autocomplete="off" placeholder="用户名"></el-input>
      </el-form-item>

      <el-form-item prop="password">
        <el-input type="password" v-model="form.password" autocomplete="off" placeholder="密码"></el-input>
      </el-form-item>
      <el-form-item prop="confirmPassword">
        <el-input type="password" v-model="form.confirmPassword" autocomplete="off" placeholder="确认密码"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm('registerForm')">注册</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
export default {
  data() {
    return {
      form: {
        username: '',

        password: '',
        confirmPassword: ''
      },
      rules: {
        username: [
          { validator: this.validateUsername, trigger: 'blur' }
        ],

        password: [
          { validator: this.validatePassword, trigger: 'blur' }
        ],
        confirmPassword: [
          { validator: this.validateConfirmPassword, trigger: 'blur' }
        ]
      }
    };
  },
  methods: {
    validateUsername(rule, value, callback) {
      if (!value) {
        return callback(new Error('请输入用户名'));
      } else {
        callback();
      }
    },

    validatePassword(rule, value, callback) {
      if (!value) {
        return callback(new Error('请输入密码'));
      } else if (value.length < 6) {
        return callback(new Error('密码至少需要6个字符'));
      } else {
        callback();
      }
    },
    validateConfirmPassword(rule, value, callback) {
      if (!value) {
        return callback(new Error('请再次输入密码'));
      } else if (value !== this.form.password) {
        return callback(new Error('两次输入的密码不一致'));
      } else {
        callback();
      }
    },

    submitForm(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          this.$http.post('https://youxuan-zua-api.tulan.wang/admin/ysf-user-info/register', this.form)
              .then(response => {
                if (response.data.status === 0) {
                  this.$message.success('注册成功！');
                  this.$router.push({ path: '/login' });
                } else {
                  this.$message.error(response.data.msg);
                }
              })
              .catch(error => {
                this.$message.error('网络错误');
              });
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    }
  }
};
</script>

<style scoped>
#register {
  width: 300px;
  margin: 150px auto;
}
.title {
  text-align: center;
}
</style>